//
//  ViewController.m
//  ClickWebImage
//
//  Created by Burn on 2019/6/12.
//  Copyright © 2019 menksoft. All rights reserved.
//

#import "ViewController.h"
#import <WebKit/WebKit.h>
#import <UIImageView+WebCache.h>

@interface ViewController ()<WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler,UIScrollViewDelegate>

@property(strong,nonatomic) WKWebView *webView;
@property(strong,nonatomic) NSMutableArray *imageUrlArr;

/*图片查看*/
@property (weak, nonatomic) UIScrollView *scrollView;
@property (weak, nonatomic) UIImageView *lastImageView;
@property (nonatomic, assign)CGRect originalFrame;
@property (nonatomic, assign)BOOL isDoubleTap;

@end

@implementation ViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.webView];
    
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://203.57.230.154:8866/menksoft-base-springmvc-webapi-inspinia/api/carousel/monglView/22"]]];
    
}

- (WKWebView *)webView{
    if (!_webView) {
        
        NSString *js = @"function getImages(){\
        var objs = document.getElementsByTagName(\"img\");\
        for(var i=0;i<objs.length;i++){\
        objs[i].onclick=function(){\
        document.location=\"myweb:imageClick:\"+this.src;\
        };\
        };\
        return objs.length;\
        };";

        
        WKUserContentController *usercc = [[WKUserContentController alloc]init];
        [usercc addScriptMessageHandler:self name:@"getImages"];
        
        WKUserScript *userScript = [[WKUserScript alloc]initWithSource:js injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        [usercc addUserScript:userScript];
        
        //  WKWebView 的配置
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc]init];
//        config.userContentController = usercc;
        
        _webView = [[WKWebView alloc]initWithFrame:self.view.bounds configuration:config];
        _webView.UIDelegate = self;
        _webView.navigationDelegate = self;
    }
    return _webView;
}










// 类似 webView 的 －webViewDidFinishLoad:
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    [self addImgClickJS];
}



// 类似 UIWebView 的 -webView: shouldStartLoadWithRequest: navigationType:
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    // 类似 UIWebView 的 -webView: shouldStartLoadWithRequest: navigationType:
    //预览图片
    NSURL * url = navigationAction.request.URL;
    if ([url.scheme isEqualToString:@"image-preview-index"]) {
        //图片点击回调
        NSInteger index = [[url.absoluteString substringFromIndex:[@"image-preview-index:" length]] integerValue];
        NSString * imgPath = self.imageUrlArr.count > index?self.imageUrlArr[index]:nil;
        NSLog(@"imgPath = %@",imgPath);
        [self lookImage:imgPath];
        decisionHandler(WKNavigationActionPolicyCancel);
    } else {
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}


- (void)addImgClickJS {
    
    //获取所以的图片标签
    [self.webView evaluateJavaScript:@"function getImages(){\
     var imgs = document.getElementsByTagName('img');\
     var imgScr = '';\
     for(var i=0;i<imgs.length;i++){\
     if (i == 0){ \
     imgScr = imgs[i].src; \
     } else {\
     imgScr = imgScr +'***'+ imgs[i].src;\
     } \
     };\
     return imgScr;\
     };" completionHandler:nil];//注入js方法
    
    __weak typeof(self)weakSelf = self;
    [self.webView evaluateJavaScript:@"getImages()" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        
        if (!error) {
            
            NSMutableArray * urlArray = result?[NSMutableArray arrayWithArray:[result componentsSeparatedByString:@"***"]]:nil;
            NSLog(@"urlArray = %@",urlArray);
            weakSelf.imageUrlArr = urlArray;
        } else {
            weakSelf.imageUrlArr = nil;
        }
    }];
    
    //添加图片点击的回调
    [self.webView evaluateJavaScript:@"function registerImageClickAction(){\
     var imgs = document.getElementsByTagName('img');\
     for(var i=0;i<imgs.length;i++){\
     imgs[i].customIndex = i;\
     imgs[i].onclick=function(){\
     window.location.href='image-preview-index:'+this.customIndex;\
     }\
     }\
     }" completionHandler:nil];
    [self.webView evaluateJavaScript:@"registerImageClickAction();" completionHandler:nil];
}

- (NSMutableArray *)imageUrlArr{
    if (!_imageUrlArr) {
        _imageUrlArr = [NSMutableArray array];
    }
    return _imageUrlArr;
}

#pragma mark - 图片查看
- (void)lookImage:(NSString *)url{
    //scrollView作为背景
    UIScrollView *bgView = [[UIScrollView alloc] init];
    bgView.frame = [UIScreen mainScreen].bounds;
    bgView.backgroundColor = [UIColor colorWithRed:248 / 255.0 green:248 / 255.0 blue:248 / 255.0 alpha:1];
    UITapGestureRecognizer *tapBg = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapBgView:)];
    [bgView addGestureRecognizer:tapBg];
    
    
    
    UIImageView *imageView = [[UIImageView alloc] init];
//    [imageView sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@"12"]];
    
    imageView.frame = [bgView convertRect:CGRectMake(0, 0, 1, 1) fromView:self.view];
    imageView.center = self.view.center;
    [bgView addSubview:imageView];
    
    [[[UIApplication sharedApplication] keyWindow] addSubview:bgView];
    
    self.lastImageView = imageView;
    self.originalFrame = imageView.frame;
    self.scrollView = bgView;
    //最大放大比例
    self.scrollView.maximumZoomScale = 2;
    self.scrollView.delegate = self;
    
    [imageView sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@"123"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        if (!error) {
            [UIView animateWithDuration:0.5 animations:^{
                CGRect frame = imageView.frame;
                frame.size.width = bgView.frame.size.width;
                frame.size.height = frame.size.width * (imageView.image.size.height / imageView.image.size.width);
                frame.origin.x = 0;
                frame.origin.y = (bgView.frame.size.height - frame.size.height) * 0.5;
                imageView.frame = frame;
            }];
        }
    }];
    
}


-(void)tapBgView:(UITapGestureRecognizer *)tapBgRecognizer
{
    self.scrollView.contentOffset = CGPointZero;
    [UIView animateWithDuration:0.5 animations:^{
        self.lastImageView.frame = self.originalFrame;
        tapBgRecognizer.view.backgroundColor = [UIColor clearColor];
    } completion:^(BOOL finished) {
        [tapBgRecognizer.view removeFromSuperview];
        self.scrollView = nil;
        self.lastImageView = nil;
    }];
}

//返回可缩放的视图
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return self.lastImageView;
}



@end
